package com.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @ClassName ProxyUtil
 * @Description 动态代理对象，aop
 * @Author 2214361854
 * @Date 2022/3/5 14:02
 * @Version 1.0
 */
public class ProxyUtil {
    public static <T> T getProxy(final T obj) {
        return (T)Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(),
            new InvocationHandler() {
                /*
                参一：类加载器
                参二：类的接口
                参三：实现InvocationHandler接口，创建代理对象
                */
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    long startTimer = System.currentTimeMillis();
                    Object result = method.invoke(obj, args);
                    long endTimer = System.currentTimeMillis();
                    System.out.println(method.getName()+"方法耗时："+(endTimer-startTimer)/1000.0+"s");
                    return result;
            }
        });
    }
}
